package com.tulele.vtool.handler;

import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.tulele.vtool.model.UserWithdrawLogInfo;
import com.tulele.vtool.model.reqEntity.ApplyWithdrawReqBean;
import com.tulele.vtool.model.reqEntity.GetWithdrawRecordInfoReqBean;
import com.tulele.vtool.model.respEntity.RespData;
import com.tulele.vtool.model.respEntity.ReturnCode;
import com.tulele.vtool.service.IUserInfoService;
import com.tulele.vtool.service.IUserWithdrawLogInfoService;
import com.tulele.vtool.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
public class UserWithdrawInfoHandler {

    @Autowired
    private IUserWithdrawLogInfoService userWithdrawLogInfoService;

    @Autowired
    private IUserInfoService userInfoService;

    @PostMapping(value = "/getUserWithdrawDesc1", produces = "application/json;charset=UTF-8")
    public RespData getUserWithdrawDesc1(@RequestHeader("userId") String userId) {

        UserWithdrawLogInfo userWithdrawLogInfo = userWithdrawLogInfoService.getUserWithdrawDesc1(Integer.parseInt(userId));

        if(userWithdrawLogInfo==null){
            userWithdrawLogInfo=new UserWithdrawLogInfo();
        }
        userWithdrawLogInfo.setAmount(0d);
        Double accountBalance = userInfoService.getUserAccountBalance(Integer.parseInt(userId));
        if(accountBalance!=null && accountBalance>0) {
            userWithdrawLogInfo.setAmount(accountBalance);
        }

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);

        Map<String, Object> resultMap = Maps.newHashMapWithExpectedSize(2);
        resultMap.put("userWithdrawLogInfo", userWithdrawLogInfo);
        respData.setData(resultMap);
        respData.setMsg("成功");
        return respData;

    }

    /**
     * 获取用户的提现记录列表
     * @param userId 用户 ID
     * @param getWithdrawRecordInfoReqBean 分页信息
     * @return 用户的提现记录列表
     */
    @PostMapping(value = "/getWithdrawRecordInfo", produces="application/json;charset=UTF-8")
    public RespData getWithdrawRecordInfo(@RequestHeader("userId") String userId, @RequestBody GetWithdrawRecordInfoReqBean getWithdrawRecordInfoReqBean) {

        Map<String, Object> queryMap = Maps.newHashMap();

        Integer pageNum = getWithdrawRecordInfoReqBean.getPageNum();
        if (pageNum == null || pageNum.intValue() <= 0) {
            pageNum = 1;
        }

        Integer pageSize = getWithdrawRecordInfoReqBean.getPageSize();
        if (pageSize == null || pageNum.intValue() <= 0) {
            pageSize = 10;
        }

        queryMap.put("pageNum", pageNum);
        queryMap.put("pageSize", pageSize);
        queryMap.put("userId", Integer.valueOf(userId));

        PageInfo<UserWithdrawLogInfo> userWithdrawInfoPageInfo = userWithdrawLogInfoService.getUserWithdrawPageInfo(queryMap);

        List<UserWithdrawLogInfo> userWithdrawLogInfoList = userWithdrawInfoPageInfo.getList();

        List<Map<String, Object>> withdrawList = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(userWithdrawLogInfoList)) {
            userWithdrawLogInfoList.forEach(info -> {

                Map<String, Object> infoMap = Maps.newHashMapWithExpectedSize(6);
                infoMap.put("withdrawDesc", info.getRemark());

                int processStatus = Optional.ofNullable(info.getProcessStatus()).orElse(0);
                infoMap.put("withdrawStatus", processStatus);

                infoMap.put("applyTime", DateUtil.getFormatDate("yyyy年MM月dd日 HH点mm分", info.getCreateTime()));

                infoMap.put("amount", Optional.ofNullable(info.getAmount()).orElse(0d));

                if (processStatus == 0) {

                    infoMap.put("transferTime", "提示：提现后三个工作日内到账.");

                } else if (processStatus == 1) {

                    infoMap.put("transferTime", DateUtil.getFormatDate("yyyy年MM月dd日 HH点mm分", info.getModifyTime()));

                } else if (processStatus == 2) {

                    infoMap.put("transferTime", "提示：提现被拒绝，请联系客服解决。");

                } else if (processStatus == 3) {

                    infoMap.put("transferTime", "提示：打款失败，请联系客服。");

                }

                withdrawList.add(infoMap);
            });
        }

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);

        Map<String, Object> resultMap = Maps.newHashMapWithExpectedSize(3);

        long count = userWithdrawInfoPageInfo.getTotal();
        resultMap.put("count", count);
        resultMap.put("items", withdrawList);

        Double userAccountBalance = userInfoService.getUserAccountBalance(Integer.valueOf(userId));
        resultMap.put("userAccountBalance", userAccountBalance);// 当前可提现金额

        respData.setData(resultMap);
        respData.setMsg("成功");
        return respData;
    }

    @PostMapping(value = "/applyWithdraw", produces="application/json;charset=UTF-8")
    public RespData applyWithdraw(@RequestHeader("userId") String userId, @RequestBody ApplyWithdrawReqBean applyWithdrawReqBean) {

        if (applyWithdrawReqBean == null || applyWithdrawReqBean.getAmount() == null) {
            RespData respData = new RespData();
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数异常");
            return respData;
        }

        UserWithdrawLogInfo userWithdrawLogInfo = new UserWithdrawLogInfo();
        userWithdrawLogInfo.setUserId(Integer.parseInt(userId));
        userWithdrawLogInfo.setAmount(applyWithdrawReqBean.getAmount().doubleValue());

        //20200314 添加账号信息等
        userWithdrawLogInfo.setFullName(applyWithdrawReqBean.getFullName());
        userWithdrawLogInfo.setBankName(applyWithdrawReqBean.getBankName());
        userWithdrawLogInfo.setSubBranch(applyWithdrawReqBean.getSubBranch());
        userWithdrawLogInfo.setBankAccount(applyWithdrawReqBean.getBankAccount());
        userWithdrawLogInfo.setPhone(applyWithdrawReqBean.getPhone());
        userWithdrawLogInfo.setQrcodeUrl(applyWithdrawReqBean.getQrcodeUrl());
        //20200314 添加账号信息等

        int result = userWithdrawLogInfoService.applyWithdrawCommission(userWithdrawLogInfo);

        if (result == ReturnCode.WITHDRAW_SHORT_OF_MONEY) {
            RespData respData = new RespData();
            respData.setCode(ReturnCode.WITHDRAW_SHORT_OF_MONEY);
            respData.setMsg("当前金额不足，请重新尝试");
            return respData;
        }

        Double accountBalance = userInfoService.getUserAccountBalance(Integer.parseInt(userId));

        Map<String,Object> res = Maps.newHashMapWithExpectedSize(2);
        res.put("accountBalance", accountBalance);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setData(res);
        respData.setMsg("成功");
        return respData;
    }

}
